<template>
  <div class="user-chat">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <button @click="handleBack" class="back-btn">
        <i class="fa fa-arrow-left"></i>
      </button>
      <h2>在线客服</h2>
      <button @click="handleLogout" class="logout-btn">
        <i class="fa fa-sign-out"></i>
      </button>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messageContainer">
      <!-- 系统提示消息 -->
      <div v-if="systemMessage" class="system-message">
        {{ systemMessage }}
      </div>

      <!-- 消息列表 -->
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message-item', msg.senderType === 1 ? 'user-message' : 'admin-message']"
      >
        <!-- 用户头像 -->
        <div v-if="msg.senderType === 1" class="avatar">
          <img :src="userAvatar" alt="我的头像">
        </div>

        <!-- 消息内容 -->
        <div :class="['message-content', msg.senderType === 1 ? 'user-content' : 'admin-content']">
          <template v-if="msg.messageType === 1">
            {{ msg.content }}
          </template>
          <template v-if="msg.messageType === 2">
            <img :src="msg.content" alt="聊天图片" class="message-image" @click="previewImage(msg.content)">
          </template>
          <span class="message-time">{{ formatTime(msg.sendTime) }}</span>
        </div>

        <!-- 客服头像 -->
        <div v-if="msg.senderType === 2" class="avatar">
          <img :src="adminAvatar" alt="客服头像">
        </div>
      </div>

      <!-- 正在输入提示 -->
      <div v-if="isAdminTyping" class="message-item admin-message">
        <div class="avatar">
          <img :src="adminAvatar" alt="客服头像">
        </div>
        <div class="message-content admin-content typing-indicator">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-tools">
        <input
            type="file"
            ref="imageInput"
            accept="image/*"
            @change="handleImageSelect"
            class="hidden"
        >
        <button @click="selectImage" class="tool-btn" aria-label="发送图片">
          <i class="fa fa-picture-o"></i>
        </button>
        <button class="tool-btn" aria-label="表情">
          <i class="fa fa-smile-o"></i>
        </button>
      </div>

      <div class="input-wrapper">
        <input
            type="text"
            v-model="messageContent"
            placeholder="输入消息..."
            @keydown.enter="sendMessage"
            @input="handleTyping"
            class="message-input"
        >
        <button @click="sendMessage" class="send-btn" :disabled="!messageContent.trim()">
          发送
        </button>
      </div>
    </div>

    <!-- 图片预览 -->
    <div v-if="previewUrl" class="image-preview" @click="closePreview">
      <img :src="previewUrl" alt="预览图片" class="preview-img">
    </div>
  </div>
</template>

<script setup>
// 脚本部分保持不变，与原代码相同
import { ref, onMounted, nextTick, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter();
const store = useStore();

// 从Vuex获取用户信息
const userId = computed(() => store.state.userId);
const userInfo = computed(() => store.state.userInfo || {});
const sessionId = computed(() => store.state.sessionId);

// 常量定义
const adminAvatar = 'https://picsum.photos/200/200?random=admin';
const userAvatar = computed(() => userInfo.value.avatar || `https://picsum.photos/200/200?random=${userId.value}`);

// 聊天状态管理
const messages = ref([]);
const messageContent = ref('');
const isAdminTyping = ref(false);
const systemMessage = ref('正在连接客服...');
const messageContainer = ref(null);
const imageInput = ref(null);
const ws = ref(null);
const typingTimer = ref(null);
const previewUrl = ref('');

// 返回上一页
const handleBack = () => {
  router.back();
};

// 登出功能
const handleLogout = () => {
  if (ws.value) {
    ws.value.close();
  }
  store.dispatch('logout');
  router.push('/user/login');
};

// 检查用户登录状态
const checkUserStatus = () => {
  if (!userId.value || !sessionId.value) {
    router.push('/user/login');
    return false;
  }
  return true;
};

// 加载历史消息
const loadHistoryMessages = () => {
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.get(`/user/messages/${sessionId.value}`, {
    params: { userId: userId.value }
  }).then(res => {
    // 适配后端MessageDTO结构
    if (res.data.data && Array.isArray(res.data.data)) {
      messages.value = res.data.data.map(msg => ({
        ...msg,
        // 确保字段映射正确
        senderType: msg.senderType || (msg.senderId === userId.value ? 1 : 2),
        messageType: msg.messageType || 1
      }));
      scrollToBottom();
    }
  }).catch(err => {
    console.error('加载历史消息失败', err);
    systemMessage.value = '加载历史消息失败';
  });
};

// 初始化WebSocket连接
const initWebSocket = () => {
  if (!checkUserStatus()) return;

  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const host = `${window.location.hostname}:9990`;
  const url = `${protocol}//${host}/ws?userId=${userId.value}&role=user&sessionId=${sessionId.value}`;

  ws.value = new WebSocket(url);

  ws.value.onopen = () => {
    console.log('用户端WebSocket连接已建立');
    systemMessage.value = '客服已连接，您可以开始聊天了';
    loadHistoryMessages();
  };

  ws.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);

      switch (data.type) {
        case 'message':
          // 处理消息格式适配后端MessageDTO
          if (data.data) {
            messages.value.push({
              ...data.data,
              senderType: data.data.senderType || 2,
              messageType: data.data.messageType || 1
            });
            systemMessage.value = '';
            scrollToBottom();
          }
          break;
        case 'typing':
          isAdminTyping.value = data.status;
          break;
        case 'system':
          systemMessage.value = data.content;
          break;
        default:
          console.log('未知消息类型', data);
      }
    } catch (e) {
      console.error('解析WebSocket消息失败', e);
    }
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
    systemMessage.value = '连接已断开，正在重连...';
    // 3秒后重连
    setTimeout(initWebSocket, 3000);
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket错误:', error);
    systemMessage.value = '连接出错，请刷新页面重试';
  };
};

// 发送消息
const sendMessage = () => {
  const content = messageContent.value.trim();
  if (content && ws.value && ws.value.readyState === WebSocket.OPEN) {
    // 构造符合后端要求的消息格式
    const message = {
      sessionId: sessionId.value,
      senderId: userId.value,
      content: messageContent.value,
      messageType: 1, // 文字消息
      senderType: 1,  // 用户发送
      sendTime: new Date().toISOString()
    };

    ws.value.send(JSON.stringify({
      type: 'typing',
      data: message
    }));

    // 添加到本地消息列表
    messages.value.push(message);
    messageContent.value = '';
    scrollToBottom();
  }
};

// 处理输入状态
const handleTyping = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    // 发送正在输入状态
    ws.value.send(JSON.stringify({
      type: 'typing',
      sessionId: sessionId.value,
      status: true,
      role: 'user'
    }));

    // 清除之前的定时器
    if (typingTimer.value) {
      clearTimeout(typingTimer.value);
    }

    // 3秒后发送停止输入状态
    typingTimer.value = setTimeout(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(JSON.stringify({
          type: 'typing',
          sessionId: sessionId.value,
          status: false,
          role: 'user'
        }));
      }
    }, 3000);
  }
};

// 选择图片
const selectImage = () => {
  imageInput.value.click();
};

// 处理图片选择
const handleImageSelect = (e) => {
  const file = e.target.files[0];
  if (file && ws.value && ws.value.readyState === WebSocket.OPEN) {
    const reader = new FileReader();
    reader.onload = (event) => {
      const base64Image = event.target.result;

      const message = {
        sessionId: sessionId.value,
        senderId: userId.value,
        content: base64Image,
        messageType: 2, // 图片消息
        senderType: 1,  // 用户发送
        sendTime: new Date().toISOString()
      };

      ws.value.send(JSON.stringify({
        type: 'message',
        data: message
      }));

      // 添加到本地消息列表
      messages.value.push(message);
      scrollToBottom();
    };
    reader.readAsDataURL(file);

    // 清空输入
    e.target.value = '';
  }
};

// 图片预览
const previewImage = (url) => {
  previewUrl.value = url;
};

// 关闭预览
const closePreview = () => {
  previewUrl.value = '';
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';

  const date = new Date(timeString);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 页面加载时初始化
onMounted(() => {
  if (!checkUserStatus()) return;
  initWebSocket();
});

// 页面卸载时清理
onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
  if (typingTimer.value) {
    clearTimeout(typingTimer.value);
  }
});
</script>

<style scoped>
/* 基础样式 */
.user-chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f7;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 聊天头部 - 手机端优化 */
.chat-header {
  background-color: #165DFF;
  color: white;
  padding: 0 15px;
  height: 56px; /* 增加高度适应手机状态栏 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.back-btn, .logout-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  /* 增加点击区域 */
  touch-action: manipulation;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  padding: 15px 10px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
  -webkit-overflow-scrolling: touch; /* 移动端平滑滚动 */
}

/* 消息项样式 */
.message-item {
  display: flex;
  align-items: flex-start;
  max-width: 85%; /* 手机端更宽的消息宽度 */
  margin: 4px 0;
  animation: fadeIn 0.2s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(5px); }
  to { opacity: 1; transform: translateY(0); }
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.admin-message {
  align-self: flex-start;
}

/* 头像样式 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-message .avatar {
  margin-left: 8px;
}

.admin-message .avatar {
  margin-right: 8px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 消息内容 */
.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  word-break: break-word;
  position: relative;
  font-size: 16px;
  line-height: 1.5;
  max-width: calc(100% - 40px);
}

.user-content {
  background-color: #165DFF;
  color: white;
  border-top-right-radius: 4px; /* 优化视觉效果 */
}

.admin-content {
  background-color: white;
  border: 1px solid #e5e5e5;
  border-top-left-radius: 4px; /* 优化视觉效果 */
}

/* 图片消息 */
.message-image {
  width: 100%;
  max-width: 220px; /* 手机端图片尺寸 */
  border-radius: 12px;
  cursor: pointer;
  touch-action: manipulation;
}

/* 时间戳
.message-time {
  position: absolute;
  bottom: 4px;
  right: 12px;
  font-size: 10px;
  color: rgba(255, 255, 255, 0.5);
}*/

.message-time {
  font-size: 11px;
  margin-top: 5px;
  display: block;
  opacity: 0.7;
}

.admin-content .message-time {
  color: rgba(0, 0, 0, 0.3);
}

/* 正在输入提示 */
.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 14px;
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) { animation-delay: 0s; }
.dot:nth-child(2) { animation-delay: 0.2s; }
.dot:nth-child(3) { animation-delay: 0.4s; }

/* 系统消息 */
.system-message {
  align-self: center;
  background-color: #f0f2f5;
  color: #666;
  padding: 6px 14px;
  border-radius: 12px;
  font-size: 13px;
  margin: 5px 0;
}

/* 输入区域 */
.input-area {
  padding: 12px 15px 20px; /* 底部增加 padding 适应手机底部 */
  background-color: white;
  border-top: 1px solid #e5e7eb;
}

.input-tools {
  display: flex;
  margin-bottom: 10px;
}

.input-tools .tool-btn {
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: #f5f5f5;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  touch-action: manipulation;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}

.input-wrapper {
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 24px;
  outline: none;
  font-size: 16px;
  min-height: 48px;
  box-sizing: border-box;
  resize: none;
  overflow: hidden;
}

.send-btn {
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 24px;
  padding: 10px 20px;
  margin-left: 10px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  white-space: nowrap;
  touch-action: manipulation;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}

.send-btn:disabled {
  background-color: #94bfff;
  cursor: not-allowed;
}

.send-btn:hover:not(:disabled) {
  background-color: #0e47d1;
}

/* 图片预览 */
.image-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
  box-sizing: border-box;
  touch-action: manipulation;
}

.preview-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 隐藏文件输入 */
.hidden {
  display: none;
}

/* 动画 */
@keyframes typing {
  0% { transform: translateY(0px); }
  28% { transform: translateY(-3px); }
  44% { transform: translateY(0px); }
}

/* 手机适配优化 */
@media (max-width: 480px) {
  .message-item {
    max-width: 90%;
  }

  .message-content {
    font-size: 15px;
    padding: 10px 14px;
  }

  .send-btn {
    padding: 9px 16px;
    font-size: 15px;
  }

  .chat-header {
    height: 54px;
  }
}

/* 小屏手机适配 */
@media (max-width: 360px) {
  .message-content {
    font-size: 14px;
    padding: 8px 12px;
  }

  .tool-btn {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }

  .message-input {
    padding: 10px 14px;
    font-size: 15px;
  }
}
</style>
